﻿
using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.FormCategory;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.FormCategory
{
    /// <summary>
    /// 新增表单类别
    /// </summary>
    public class CreateFormCategoryHandler : IRequestHandler<CreateFormCategoryCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<FormCategoryModel> formCategoryRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateFormCategoryHandler> logger;

        public CreateFormCategoryHandler(IBaseRepository<FormCategoryModel> formCategoryRepo,IMapper mapper,ILogger<CreateFormCategoryHandler> logger )
        {
            this.formCategoryRepo = formCategoryRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(CreateFormCategoryCommand request, CancellationToken cancellationToken)
        {
            var model = mapper.Map<FormCategoryModel>(request);//把请求命令通过automapper 转成实体

            model.Id = YitIdHelper.NextId();

            NewCode(model);

            int r = await formCategoryRepo.CreateAsync(model);

            if (r > 0)
            {
                return new ApiResult<int>().Success("添加表单类别成功", r);
            }
            else
            {
                return new ApiResult<int>().Fail("添加表单类别失败");
            }
        }

        private void NewCode(FormCategoryModel model)
        {
            var count = formCategoryRepo.GetAll().Count() + 1;//不能过滤已逻辑删除
            string code = "T" + count.ToString().PadLeft(4, '0');
            model.FormCategoryCode = code;
        }
    }
}
